package cn.haulon.express.kuaidi100;

import cn.haulon.express.Express;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Created by Haulon on 18/09/2017.
 * <p>
 * Used as 快递100单号查询
 */
public class Kuaidi100Express implements Express {
    private static String baseUrl = "https://www.kuaidi100.com/";  // 快递100地址
    private static String checkUrl = baseUrl + "chaxun"; // 跳转路径
    private static String autoUrl = baseUrl + "autonumber/autoComNum"; // 自动匹配API
    private static String queryUrl = baseUrl + "query"; // 查询API
    private static final int timeout = 1000; // 1秒超时

    public Kuaidi100Express() {
        initCompanyName();
    }

    @Override
    public Object query(String number) {
        try {
            Document document = Jsoup.connect(autoUrl).data("text", number).timeout(timeout).get();
            JSONObject json = JSON.parseObject(document.body().text());
            String type = json != null && json.getJSONArray("auto").size() > 0 ?
                    ((JSONObject) json.getJSONArray("auto").get(0)).getString("comCode") : "";
            return query(type, number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object query(String type, String number) {
        try {
            Document document = Jsoup.connect(queryUrl).data("type", type, "postid", number).timeout(timeout).get();
            return document.body().text();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("WeakerAccess")
    public String getCompanyName(String number) {
        try {
            Document document = Jsoup.connect(checkUrl).data("nu", number).timeout(timeout).get();
            Element element = document.body().getElementById("selectComBtn");
            return element == null ? null : element.attr("title");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void initCompanyName() {
        try {
            Document document = Jsoup.connect(baseUrl).data("from", "openv").timeout(timeout).get();
            Elements elements = document.body().getElementsByAttribute("data-code").tagName("a");
            Kuaidi100Code code = new Kuaidi100Code();
            elements.forEach(element -> code.set(element.attr("data-code"), element.text()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
